package com.hopes.bizz.common.core.validate;


import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Iterator;
import java.util.Set;

/**
 * @author lyb
 * @version 1.0
 * @date 2023/3/20 15:55
 */
public class ValidatorUtils {

    private static final Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     */
    public static String validateEntity(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            final Iterator<ConstraintViolation<Object>> iterator = constraintViolations.iterator();
            final StringBuilder stringBuilder = new StringBuilder();
            while (iterator.hasNext()) {
                final ConstraintViolation<Object> next = iterator.next();
                if (stringBuilder.length() == 0) {
                    stringBuilder.append(next.getMessage());
                } else {
                    stringBuilder.append("\n").append(next.getMessage());
                }
            }
            return stringBuilder.toString();
        }
        return null;
    }

    public static String validateEntity(Object object, CharSequence delimiter, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            final Iterator<ConstraintViolation<Object>> iterator = constraintViolations.iterator();
            final StringBuilder stringBuilder = new StringBuilder();
            while (iterator.hasNext()) {
                final ConstraintViolation<Object> next = iterator.next();
                if (stringBuilder.length() == 0) {
                    stringBuilder.append(next.getMessage());
                } else {
                    stringBuilder.append(delimiter).append(next.getMessage());
                }
            }
            return stringBuilder.toString();
        }
        return null;
    }

    /**
     * 校验数据、返回校验结果
     *
     * @param entity 对象
     * @param groups 分组校验
     * @return 校验结果
     */
    public static <T> String importValidateEntity(T entity, Class<?>... groups) {
        final StringBuilder res = new StringBuilder();
        final Set<ConstraintViolation<T>> constraintViolations = validator.validate(entity, groups);
        if (!constraintViolations.isEmpty()) {
            for (ConstraintViolation<T> next : constraintViolations) {
                if (res.length() == 0) {
                    res.append(next.getMessage());
                } else {
                    res.append("\n").append(next.getMessage());
                }
            }
        }
        return res.toString();
    }


}
